using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
using UnityEngine;

public class TimeRestrict : MonoBehaviour
{

    string Date = "";

    private void Start()
    {

        TimeEncryption();

        //StartCoroutine(ICheckLoop());
    }

    public void TimeEncryption()
    {
        DateTime now = DateTime.Now;
        DateTime endTime = DateTime.Parse(Decrypt(XmlConfig.GetInstance().Time));
        TimeSpan leftTime = endTime - now;

        if (leftTime.TotalDays < 0)
        {
            WriteLog.instance.WriteInfo($"加密已到期:{leftTime.TotalDays}日");
            Application.Quit();

        }
        else
        {
            Debug.Log($"加密到期剩余:{leftTime.TotalDays}日");
        }

        UpdatePlayerPrefsDate(now.Year, now.Month, now.Day);

        //Date = Decrypt(XmlConfig.GetInstance.Time);
        //CheckExpirationDate(now.Year, now.Month, now.Day, Date.Split('-'));


    }

    private void CheckExpirationDate(int year, int month, int day, string[] dateArray)
    {
        int expirationYear = Convert.ToInt32(dateArray[0]);
        int expirationMonth = Convert.ToInt32(dateArray[1]);
        int expirationDay = Convert.ToInt32(dateArray[2]);

        if (year > expirationYear)
        {
            WriteLog.instance.WriteInfo("加密到期:年");
            Application.Quit();
        }
        else if (year == expirationYear)
        {
            if (month > expirationMonth)
            {
                WriteLog.instance.WriteInfo("加密到期:月");
                Application.Quit();
            }
            else if (month == expirationMonth)
            {
                if (day > expirationDay)
                {
                    WriteLog.instance.WriteInfo("加密到期:日");
                    Application.Quit();
                }
            }
        }
    }

    private void UpdatePlayerPrefsDate(int year, int month, int day)
    {
        int previousYear = PlayerPrefs.GetInt("year");
        int previousMonth = PlayerPrefs.GetInt("month");
        int previousDay = PlayerPrefs.GetInt("day");

        if (year > previousYear)
        {
            PlayerPrefs.SetInt("year", year);
            PlayerPrefs.DeleteKey("month");
            PlayerPrefs.DeleteKey("day");
        }
        else if (year == previousYear)
        {
            if (month > previousMonth)
            {
                PlayerPrefs.SetInt("month", month);
                PlayerPrefs.DeleteKey("day");
            }
            else if (month == previousMonth)
            {
                if (day < previousDay)
                {
                    WriteLog.instance.WriteInfo("Prefs日退出，请勿修改电脑系统时间！");
                    Application.Quit();
                }
                PlayerPrefs.SetInt("day", day);
            }
            else
            {
                WriteLog.instance.WriteInfo("Prefs月退出，请勿修改电脑系统时间！");
                Application.Quit();
            }
        }
        else
        {
            WriteLog.instance.WriteInfo("Prefs年退出，请勿修改电脑系统时间！");
            Application.Quit();
        }
    }


    /// <summary>
    /// 读取xml文件，获取加密时间
    /// </summary>
    /// <returns></returns>
    public string ReadDate()
    {
        string _date = "";
        string filepath = Application.streamingAssetsPath + @"/Config.xml";
        if (File.Exists(filepath))
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(filepath);
            XmlNode root = xmlDoc.SelectSingleNode("Time");
            _date = root.InnerText.ToString().Trim();
            string s = Decrypt(_date);
            return s;
        }
        else
        {
            return _date = "2000-01-01";
        }


    }


    #region 加密解密
    private string keyValue = "01234567890123456789012345670258";
    /// <summary>
    /// 加密
    /// </summary>
    /// <param name="_input">在输入框中需要加密内容</param>
    /// <param name="_keyValue"></param>
    /// <returns></returns>
    private string Encryption(string _input)
    {
        /// <summary>
        /// 32位任意数值，作为是加密解码约定数字
        /// </summary>


        byte[] keyArray = UTF8Encoding.UTF8.GetBytes(keyValue);

        //加密格式
        RijndaelManaged encryption = new RijndaelManaged();
        encryption.Key = keyArray;
        encryption.Mode = CipherMode.ECB;
        encryption.Padding = PaddingMode.PKCS7;

        //生成加密锁
        ICryptoTransform cTransform = encryption.CreateEncryptor();
        byte[] _EncryptArray = UTF8Encoding.UTF8.GetBytes(_input);
        byte[] resultArray = cTransform.TransformFinalBlock(_EncryptArray, 0, _EncryptArray.Length);
        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }

    /// <summary>
    /// 解密
    /// </summary>
    /// <param name="_valueDense"></param>
    /// <param name="_keyValue"></param>
    /// <returns></returns>
    private string Decrypt(string _valueDense)
    {
        byte[] keyArray = UTF8Encoding.UTF8.GetBytes(keyValue);

        RijndaelManaged decipher = new RijndaelManaged();
        decipher.Key = keyArray;
        decipher.Mode = CipherMode.ECB;
        decipher.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = decipher.CreateDecryptor();
        try
        {
            byte[] _EncryptArray = Convert.FromBase64String(_valueDense);
            byte[] resultArray = cTransform.TransformFinalBlock(_EncryptArray, 0, _EncryptArray.Length);
            return UTF8Encoding.UTF8.GetString(resultArray);
        }
        catch (Exception)
        {
            WriteLog.instance.WriteInfo("加密解析失败，请检查配置文件");
            Application.Quit();
            throw;
        }

    }
    #endregion

    #region 联网加密
    //StartCoroutine(ICheckLoop());
    //IEnumerator ICheckLoop()
    //{

    //    UnityWebRequest www = UnityWebRequest.Get(@"http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp");
    //    yield return www.SendWebRequest();
    //    if (string.IsNullOrEmpty(www.error))
    //    {
    //        //Debug.Log(www.downloadHandler.text);
    //        JSONNode node = JSONNode.Parse(www.downloadHandler.text);
    //        string t = node["data"]["t"];
    //        DateTime time = GetDateTime(long.Parse(t));
    //        if (time.Year == 2021 && time.Month <= 10)
    //        {
    //            if (time.Day <= 24)
    //            {
    //                Debug.Log("****************in");
    //            }
    //            else
    //            {
    //                Debug.Log("****************out");
    //                Application.Quit();
    //            }

    //        }
    //        else
    //        {
    //            Debug.Log("****************out");
    //            Application.Quit();
    //        }
    //    }
    //    else
    //    {
    //        Debug.Log("****************out");
    //        Application.Quit();
    //    }
    //    //for (int i = 0; i < 5; i++)
    //    //{
           
    //    //    yield return new WaitForSeconds(1);
    //    //}
    //}

    public static DateTime GetDateTime(long timestamp)
    {
        var startTime = TimeZoneInfo.ConvertTime(new DateTime(1970, 1, 1), TimeZoneInfo.FindSystemTimeZoneById("China Standard Time"));
        //var startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
        return startTime.AddMilliseconds(timestamp);
    }
    #endregion

    #region 16进制转换
    ///// <summary>
    ///// 字符串转16进制
    ///// </summary>
    ///// <param name="input">要转格式的字符串</param>
    ///// <returns>转化为16进制的字符串</returns>
    //private string ToSixteen(string input)
    //{
    //    char[] values = input.ToCharArray();
    //    string end = string.Empty;
    //    foreach (char letter in values)
    //    {
    //        int value = Convert.ToInt32(letter);
    //        string hexoutput = string.Format("{0:X}", value); //0 表示占位符 x或X表示十六进制
    //        end += hexoutput + "_";
    //    }
    //    end = end.Remove(end.Length - 1);
    //    return end;
    //}

    ///// <summary>
    ///// 16进制转回字符串
    ///// </summary>
    ///// <param name="input">16进制</param>
    ///// <returns>转回的字符串</returns>
    //private string ToMyString(string input)
    //{
    //    string[] hexvaluesplit = input.Split('_');
    //    string end = string.Empty;
    //    foreach (string hex in hexvaluesplit)
    //    {
    //        int value = Convert.ToInt32(hex, 16);
    //        string stringvalue = char.ConvertFromUtf32(value);
    //        char charValue = (char)value;
    //        end += charValue;
    //    }
    //    return end;
    //}
    #endregion
}


